package com.easyfun.healthmagicbox.comm;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.comm.json.PersonQuestionsListJsonWrapper;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.ormlite.ServerResponseCode;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.HealthInputData;
import com.easyfun.healthmagicbox.pojo.PersonQuestion;
import com.easyfun.healthmagicbox.sync.CommCallback;
import com.j256.ormlite.dao.Dao;

public class PersonQuestionsUploadTask extends BaseRedoTask implements Runnable, DatabaseAccess{

	String mpersonalID;
	String doctorID;
	String question;
	String questionTime;
	
	//For redo task
	public PersonQuestionsUploadTask(Context context,CommCallback callback)
	{
		super(context,callback);
	}
	
	public PersonQuestionsUploadTask(Context context,CommCallback callback, String persionID,
									 String doctorID, String question,String questionTime)
	{

		super(context,callback);
		this.doctorID = doctorID;
		this.question = question;
		this.questionTime = questionTime;
		mpersonalID = persionID;
	}

	@Override
	public void run() {
		
		if ((mpersonalID==null)||(mpersonalID.length()==0))
			return;
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("personID", mpersonalID);
			map.put("syncid", 0);		//find out unsync data
			Dao<PersonQuestion, Integer> questionDao = getHelper(mcontext).getQuestionsDao();
			List<PersonQuestion> pps = questionDao.queryForFieldValues(map);
			String tmp;
			String result;
			if(pps.size() > 0)
			{
				PersonQuestionsListJsonWrapper<?> wrapper = new PersonQuestionsListJsonWrapper(
						pps);
				tmp = wrapper.serialize();

				Map<String, String> parmas = new HashMap<String, String>();
				parmas.put("jsonstring", tmp);
				
				result = super.uploadByHTTP(parmas,ConstantData.PersonQuestionPOSTURI);
				
 				if (ServerResponseCode.parseOf(result)==ServerResponseCode.FAILED)
				{
					ccb.setCommResult(this,
							"", ServerResponseCode.FAILED);
					return;
				}
				if (result.length()>0) {
					String[] ss=result.split("\\,");
			        int i=0;
			        
					int size = ss.length;// 3 & 5
					if (size != pps.size()) {
						// the count is not match result is failed.
						ccb.setCommResult(this,
								"",ServerResponseCode.FAILED);
					} else {
						while(i<ss.length)
				        {
							String[] idPairs = ss[i].split("\\:");
							for(int m = 0; m < pps.size(); m ++) {
								if(pps.get(m).getId() == Integer.valueOf(idPairs[0])) {
									if(idPairs[1] != null) {
										List<PersonQuestion> data = questionDao.queryForEq("syncid", idPairs[1]);
										if(data.size() > 0) {
											questionDao.delete(pps.get(m));
										} else{
											pps.get(m).setSyncid(Integer.valueOf(idPairs[1]));
											questionDao.createOrUpdate(pps.get(m));
										}
									}
								}
							}
							i++;
						}
						ccb.setCommResult(this,
								mpersonalID, ServerResponseCode.SUCCESS);
					}
					return;
				}else
				{
					ccb.setCommResult(this,
							"",ServerResponseCode.FAILED);
					return;
				}
				
			}else
			{
				ccb.setCommResult(this,
						"",ServerResponseCode.NOMORE);
			}
				
			
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			ccb.setCommResult(this, mpersonalID,
					ServerResponseCode.FAILED);
		}

	}

	@Override
	public String serializeParam() throws IllegalArgumentException{
		
		return mpersonalID+BaseRedoTask.ContentsSeperator
				+doctorID+BaseRedoTask.ContentsSeperator
				+question+BaseRedoTask.ContentsSeperator
				+questionTime;
	}

	@Override
	public void deserializeParam(String serialstring) throws IllegalArgumentException{
		String[] tmp = serialstring.split(BaseRedoTask.regExHead + BaseRedoTask.ContentsSeperator);
		if (tmp.length == 4)
		{
			mpersonalID = tmp[0];
			doctorID = tmp[1];
			question = tmp[2];
			questionTime = tmp[3];
			return;
		}else
		{
			throw new IllegalArgumentException("param length is not 4");
		}
		
	}
	
	@Override
	public DatabaseHelper getHelper(Context context) {
		return DatabaseAccessImplementation.getInstance().getHelper(mcontext);
	}

}
